/*
 * MDISistema.java
 *
 * Created on September 23, 2008, 10:14 AM
 */

import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import meu.projeto.util.Conexao;

/**
 * Classe principal, de onde a aplicação inicia. <br/> No evento de WindowOpened
 * (abertura da janela) o sistema faz a conexão com o SGBD. No evento de
 * WindowClosing o sistema fecha a conexão com o SGBD.
 *
 * @author matheus
 */
public class MDISistema extends javax.swing.JFrame {

    private JanelaCadastrar janelaCadastrar;
    private static Connection conexao;

    /**
     * Creates new form MDISistema
     */
    public MDISistema() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        desktopPane = new javax.swing.JDesktopPane();
        menuBar = new javax.swing.JMenuBar();
        Cadastros = new javax.swing.JMenu();
        mnCadastrar = new javax.swing.JMenuItem();
        mnLookandFill = new javax.swing.JMenu();
        jSeparator3 = new javax.swing.JSeparator();
        jSeparator4 = new javax.swing.JSeparator();
        jSeparator1 = new javax.swing.JSeparator();
        exitMenuItem = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("MDX - Sistema de armazenamento de dados");
        setPreferredSize(new java.awt.Dimension(750, 800));
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        Cadastros.setText("Menu");

        mnCadastrar.setText("Cadastrar");
        mnCadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnCadastrarActionPerformed(evt);
            }
        });
        Cadastros.add(mnCadastrar);

        mnLookandFill.setText("Estilo");
        mnLookandFill.add(jSeparator3);
        mnLookandFill.add(jSeparator4);

        Cadastros.add(mnLookandFill);
        Cadastros.add(jSeparator1);

        exitMenuItem.setText("Sair");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        Cadastros.add(exitMenuItem);

        menuBar.add(Cadastros);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(desktopPane, javax.swing.GroupLayout.DEFAULT_SIZE, 775, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(desktopPane, javax.swing.GroupLayout.PREFERRED_SIZE, 811, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-791)/2, (screenSize.height-681)/2, 791, 681);
    }// </editor-fold>//GEN-END:initComponents

private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
// TODO add your handling code here:
    try {
        MDISistema.conexao = Conexao.get();
        Login dialog = new Login(this, true);
        dialog.setVisible(true);
    } catch (SQLException ex) {
        JOptionPane.showInternalMessageDialog(this.desktopPane, String.format("Erro ao conectar ao SGBD: %s", ex.getMessage()), "Erro", JOptionPane.ERROR_MESSAGE);
        Logger.getLogger(MDISistema.class.getName()).log(Level.SEVERE, null, ex);
        System.exit(1);
    } catch (ClassNotFoundException ex) {
        JOptionPane.showInternalMessageDialog(this.desktopPane, "Erro ao carregar o Drive do SGBD", "Erro", JOptionPane.ERROR_MESSAGE);
        Logger.getLogger(MDISistema.class.getName()).log(Level.SEVERE, null, ex);
        System.exit(2);
    }

    final JFrame frame = this;
    UIManager.installLookAndFeel("napkin", "net.sourceforge.napkinlaf.NapkinLookAndFeel");

    UIManager.LookAndFeelInfo[] listaLook = UIManager.getInstalledLookAndFeels();
    for (UIManager.LookAndFeelInfo look : listaLook) {
        UIManager.installLookAndFeel(null, null);
        JMenuItem mn = new JMenuItem(look.getName());
        mn.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                JMenuItem mnSelecionado = (JMenuItem) evt.getSource();

                UIManager.LookAndFeelInfo[] looksDisponiveis = UIManager.getInstalledLookAndFeels();
                for (UIManager.LookAndFeelInfo look : looksDisponiveis) {
                    if (mnSelecionado.getText().equals(look.getName())) {
                        try {
                            UIManager.setLookAndFeel(look.getClassName());
                            SwingUtilities.updateComponentTreeUI(frame);
                        } catch (ClassNotFoundException ex) {
                            Logger.getLogger(MDISistema.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (InstantiationException ex) {
                            Logger.getLogger(MDISistema.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (IllegalAccessException ex) {
                            Logger.getLogger(MDISistema.class.getName()).log(Level.SEVERE, null, ex);
                        } catch (UnsupportedLookAndFeelException ex) {
                            Logger.getLogger(MDISistema.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            }
        });
        this.mnLookandFill.add(mn);
    }
}//GEN-LAST:event_formWindowOpened

private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing


    try {
        conexao.close();
    } catch (SQLException ex) {
        Logger.getLogger(MDISistema.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NullPointerException ex) {
    }
}//GEN-LAST:event_formWindowClosing

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        System.exit(0);
    }//GEN-LAST:event_exitMenuItemActionPerformed

    private void mnCadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnCadastrarActionPerformed
        if (this.janelaCadastrar == null) {
            this.janelaCadastrar = new JanelaCadastrar(this);
            this.desktopPane.add(this.janelaCadastrar);
        }
        this.openJanela(this.janelaCadastrar); //---------------------------------------------------------
    }//GEN-LAST:event_mnCadastrarActionPerformed

    private void openJanela(JComponent obj) {
        if (!obj.isVisible()) {
            if (!obj.isValid()) {
                desktopPane.add(obj);
            }

            obj.setVisible(true);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MDISistema().setVisible(true);
            }
        });
    }

    /**
     * Retorna a conexão com a base de dados, realizada na abertura do MDI
     *
     * @return Conexão JDBC pronta
     */
    public static Connection getConexao() {
        return conexao;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenu Cadastros;
    private javax.swing.JDesktopPane desktopPane;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem mnCadastrar;
    private javax.swing.JMenu mnLookandFill;
    // End of variables declaration//GEN-END:variables
}
